<script setup lang="ts">
  import { computed, PropType, ref, watch } from 'vue'
  import _ from 'lodash'
  import { useDetectResultSave } from '@/services/pages/return-factory/useReturnFactory'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { ElTable, ElTableColumn, ElInput, UploadFile } from 'element-plus'
  import videoCover from '@/assets/image/pages/order/new/video.png'
  import VideoPreview from '@/views/return-factory/repair/form/components/custom-info/VideoPreview.vue'
  import { RepairGoodListItem, RepairGoodListItemExtend } from './types'
  import useDetectResultSubmitService from '@/services/module/return-factory/useDetectResultSubmitService'
  import HFilePreview from '@/components/common/file-preview/index.vue'
  import { fileUpload } from '@/api/upload'

  const { submitForm, submitLoading, submit } = useDetectResultSubmitService()
  const { saveParam, saveLoading, save } = useDetectResultSave()

  defineOptions({
    name: 'DetectionResultFillModalDetectionDetail',
  })

  const props = defineProps({
    goodList: {
      type: Array as PropType<Array<ReturnFactoryDetectGood>>,
      required: true,
    },
    detectId: {
      type: String,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
  }>()

  // 视频预览链接列表
  const videoPreviewUrls = ref<Array<string>>([])

  // 预览视频索引
  const videoPreviewIndex = ref(0)

  // 预览视频弹窗显示状态
  const videoPreviewModalVisible = ref(false)

  // 填写检测报告抽屉显示状态
  const visible = defineModel('visible', { type: Boolean, default: false })

  // 产品列表
  const _goodList = ref<Array<RepairGoodListItem>>([])
  const fileUploading = ref(false)

  /**
   * 隐藏抽屉事件
   */
  const hideDrawer = () => {
    _goodList.value.length = 0
    visible.value = false
  }

  const onConfirm = async () => {
    if (_goodList.value.some((item) => !item.file.url)) {
      HMessageBox.error('请上传检测附件')
      return
    }

    saveParam.value.length = 0
    fileUploading.value = true
    for (let i = 0; i < _goodList.value.length; i++) {
      const good = _goodList.value[i]
      if (good.file.file) {
        const uploadFileRes = await fileUpload([good.file.file])
        _goodList.value[i].file.url = uploadFileRes.data.data.rows[0]
      }
    }
    saveParam.value = _goodList.value.map((good) => {
      return {
        checkResult: good.formCheckResult,
        handleOpinion: good.formHandleOpinion,
        id: good.id,
        measure: good.formMeasure,
        recommend: good.formRecommend,
        repairGoodsId: good.repairGoodsId,
        checkResultFile: good.file.url,
      }
    })
    fileUploading.value = false
    const res = await save(props.detectId)
    if (res.code === 20000) {
      HMessage.success('填写检测结果成功')
      hideDrawer()
      emits('update')
      return
    }

    HMessageBox.error(res.message)
  }

  const onSubmit = async () => {
    if (_goodList.value.some((item) => !item.file.url)) {
      HMessageBox.error('请上传检测附件')
      return
    }

    saveParam.value.length = 0
    fileUploading.value = true
    for (let i = 0; i < _goodList.value.length; i++) {
      const good = _goodList.value[i]
      if (good.file.file) {
        const uploadFileRes = await fileUpload([good.file.file])
        _goodList.value[i].file.url = uploadFileRes.data.data.rows[0]
      }
    }
    submitForm.value = _goodList.value.map((good) => {
      return {
        checkResult: good.formCheckResult,
        handleOpinion: good.formHandleOpinion,
        id: good.id,
        measure: good.formMeasure,
        recommend: good.formRecommend,
        repairGoodsId: good.repairGoodsId,
        checkResultFile: good.file.url,
      }
    })
    fileUploading.value = false
    const res = await submit(props.detectId)
    if (res) {
      if (res.code === 20000) {
        HMessage.success('操作成功')
        hideDrawer()
        emits('update')
        return
      }

      HMessageBox.error(res.message)
      return
    }

    HMessageBox.error('提交检测结果失败')
  }

  // 表格图片列的列宽
  const tablePictureColumnWidth = computed(() => {
    const max = Math.max(..._goodList.value.map((good) => good.repairGoodsImages.length))
    return (max || 1) * 75
  })

  // 表格视频列的列宽
  const tableVideoColumnWidth = computed(() => {
    const max = Math.max(..._goodList.value.map((good) => good.repairGoodsVideos.length))
    return (max || 1) * 75
  })

  /**
   * 视频预览事件
   * @param {Number} index - 产品索引
   */
  const handlePreviewVideo = (index: number) => {
    videoPreviewUrls.value = _goodList.value[index].repairGoodsVideos
    videoPreviewIndex.value = index
    videoPreviewModalVisible.value = true
  }

  const handleUploadFile = (file: UploadFile, index: number) => {
    if (file.raw) {
      _goodList.value[index].file = {
        file: file.raw,
        url: URL.createObjectURL(file.raw),
        name: file.name,
      }
    }
  }

  const handleDeleteFile = (rowIndex: number) => {
    _goodList.value[rowIndex].file = {
      file: null,
      url: '',
      name: '',
    }
  }

  watch(
    visible,
    (value) => {
      if (value) {
        _goodList.value = _.cloneDeep(
          props.goodList.map((item) => {
            const extend: RepairGoodListItemExtend = {
              formCheckResult: item.checkResult || '',
              formHandleOpinion: [1, 2, 3, 4].includes(Number(item.handleOpinion))
                ? (Number(item.handleOpinion) as 1 | 2 | 3 | 4)
                : 1,
              formMeasure: [1, 2, 3, 4, 5].includes(Number(item.measure))
                ? (Number(item.measure) as 1 | 2 | 3 | 4 | 5)
                : 1,
              formRecommend: [1, 2, 3, 4, 5].includes(Number(item.measure))
                ? (Number(item.recommend) as 1 | 2 | 3 | 4 | 5)
                : 1,
              formRepairGoodsId: item.repairGoodsId,
              file: {
                file: null,
                url: item.checkResultFile || '',
                name: ((item.checkResultFile || '').split('/') || []).pop() || '',
              },
            }

            return Object.assign(item, extend)
          }),
        )
      }
    },
    { immediate: true },
  )
</script>

<template>
  <h-drawer
    v-model="visible"
    title="填写检测报告"
    :width="1200"
    unit="px"
    :loading="saveLoading || submitLoading || fileUploading"
    @close="hideDrawer"
  >
    <el-table stripe :border="true" :data="_goodList">
      <!-- 序号 -->
      <el-table-column type="index" fixed="left" :align="'center'" width="50" label="序号" />

      <!-- 条码 -->
      <el-table-column label="条码" prop="snCode" width="100" show-overflow-tooltip />

      <!-- 产品类型 -->
      <el-table-column label="产品类型" prop="goodsModel" width="100" show-overflow-tooltip>
        <template #default="{ row }">
          {{ row.type === 1 ? '成品' : '配件' }}
        </template>
      </el-table-column>

      <!-- 产品编号 -->
      <el-table-column label="产品编号" prop="goodsCode" width="100" show-overflow-tooltip />

      <!-- 产品型号 -->
      <el-table-column label="产品型号" prop="goodsModel" width="100" show-overflow-tooltip />

      <!-- 产品规格 -->
      <el-table-column label="产品规格" prop="goodsSpecName" width="100" show-overflow-tooltip />

      <!-- 质保开始 -->
      <el-table-column label="质保开始" prop="warrantyStartTime" width="140" />

      <!-- 质保结束 -->
      <el-table-column label="质保结束" prop="warrantyEndTime" width="140" />

      <!-- 返厂图片 -->
      <el-table-column label="返厂图片" :width="tablePictureColumnWidth">
        <template #default="{ row }">
          <div class="image-list">
            <h-image
              v-for="(img, index) in row.repairGoodsImages"
              :key="index"
              :show-del-btn="false"
              :src="img"
              :preview-src-list="row.images"
              :padding="2"
              :width="60"
              :height="37.5"
              :initial-index="index"
            />
          </div>
        </template>
      </el-table-column>

      <!-- 返厂视频 -->
      <el-table-column label="返厂视频" :width="tableVideoColumnWidth">
        <template #default="{ row }">
          <div class="image-list">
            <h-image
              v-for="(video, index) in row.repairGoodsVideos"
              :key="index"
              :show-del-btn="false"
              :is-show-img-preview="false"
              :src="videoCover"
              :padding="2"
              :width="60"
              :height="37.5"
              :initial-index="index"
              @preview="handlePreviewVideo(index)"
            />
          </div>
        </template>
      </el-table-column>

      <!-- 检测结果 -->
      <el-table-column label="检测结果" width="360">
        <template #default="{ row }">
          <el-input
            v-model.trim="row.formCheckResult"
            :disabled="row.isAfterSaleDept"
            placeholder="请输入检测结果"
            maxlength="500"
            type="textarea"
            show-word-limit
            resize="both"
          />
        </template>
      </el-table-column>

      <!-- 责任判定 -->
      <el-table-column label="责任判定" width="120">
        <template #default="{ row }">
          <el-select
            v-model="row.formHandleOpinion"
            :disabled="row.isAfterSaleDept"
            placeholder="请选择责任判定"
          >
            <el-option :value="1" label="公司责任" />
            <el-option :value="2" label="用户责任" />
            <!-- <el-option :value="3" label="维修责任" /> -->
            <el-option :value="4" label="其他" />
          </el-select>
        </template>
      </el-table-column>

      <!-- 处理意见 -->
      <!-- <el-table-column label="处理意见" width="120">
        <template #default="{ row }">
          <el-select
            v-model="row.formMeasure"
            :disabled="row.isAfterSaleDept"
            placeholder="请选择处理意见"
          >
            <el-option :value="1" label="标准退货" />
            <el-option :value="2" label="免费退货" />
            <el-option :value="3" label="维修退货" />
            <el-option :value="4" label="换货" />
            <el-option :value="5" label="退货记录" />
          </el-select>
        </template>
      </el-table-column> -->

      <!-- 处理判定 -->
      <el-table-column label="处理判定" width="120">
        <template #default="{ row }">
          <el-select v-model="row.formRecommend" placeholder="请选择处理判定">
            <el-option :value="1" label="标准退货" />
            <!-- <el-option :value="2" label="免费退货" /> -->
            <el-option :value="3" label="维修退货" />
            <el-option :value="4" label="换货" />
            <el-option :value="5" label="退货记录" />
          </el-select>
        </template>
      </el-table-column>

      <!-- 检测附件 -->
      <el-table-column label="检测附件" width="140">
        <template #header>
          <div>
            <span style="color: #f56c6c">*</span>
            <span>检测附件</span>
          </div>
        </template>
        <template #default="{ $index, row }">
          <el-upload
            v-if="!row.file.url"
            action="#"
            multiple
            accept="*"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="(file: UploadFile) => handleUploadFile(file, $index)"
            drag
            class="file"
          >
            <el-icon :size="24" color="#007cff">
              <UploadFilled />
            </el-icon>
          </el-upload>
          <div v-if="row.file.url" style="display: flex; column-gap: 6px">
            <div style="flex: 1; width: 0">
              <h-file-preview :file-url="row.file.url" :file-name="row.file.name" />
            </div>
            <h-link type="error" @click="handleDeleteFile($index)">删除</h-link>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <h-button is-modal type="primary" @click="onConfirm">保存</h-button>
      <h-button is-modal type="primary" @click="onSubmit">提交</h-button>
      <h-button is-modal @click="hideDrawer">取消</h-button>
    </template>

    <video-preview
      v-model:visible="videoPreviewModalVisible"
      :video-list="videoPreviewUrls"
      :initial-index="videoPreviewIndex"
    />
  </h-drawer>
</template>

<style scoped lang="scss">
  :deep(.el-textarea__inner) {
    width: 335px !important;
    min-height: 28px !important;
    height: 28px;
    max-height: 370px;
  }

  .image-list {
    display: flex;
    column-gap: 5px;
  }

  .file {
    width: 60px;
    height: 37.5px;

    :deep(.el-upload) {
      width: 100%;
      height: 100%;

      .el-upload-dragger {
        padding: 0;
        width: 100%;
        height: 100%;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
      }
    }
  }
</style>
